<template>
  <div class="article-template-container">
    <el-form
      ref="form"
      :model="articleForm"
      :rules="rules"
      label-position="top"
    >
      <el-form-item prop="title" label="文章标题">
        <el-input
          v-model="articleForm.title"
          placeholder="请输入文章标题"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="文章编辑"
        prop="htmlContent"
        class="editor-container"
      >
        <Editor
          ref="editorRef"
          :initialValue="articleForm.htmlContent"
          height="600px"
          :options="{ minHeight: '300px', language: 'zh-CN' }"
        />
      </el-form-item>
      <el-form-item label="文章描述" prop="description">
        <el-input
          class="textarea-input"
          type="textarea"
          v-model="articleForm.description"
          placeholder="请输入文章标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="文章头图">
        <div class="uploadimg-container">
          <UploadImg v-model="uploadimg" @onload="articleForm.thumb = $event" />
        </div>
      </el-form-item>
      <el-form-item label="文章分类" prop="categoryId">
        <el-select
          v-model="articleForm.categoryId"
          @change="handlerSelectChange"
        >
          <el-option
            v-for="c in categoryList"
            :key="c.id"
            :label="c.name"
            :value="c.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" @click="handlerSubmitArticle">{{
          mode === "edit" ? "更新文章" : "发布文章"
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import UploadImg from "@/components/UploadImg";
import "@toast-ui/editor/dist/toastui-editor.css";
import "@toast-ui/editor/dist/i18n/zh-cn";
import { Editor } from "@toast-ui/vue-editor";
import { setDevImg } from "@/utils";
import {
  getArticleCategoryAPI,
  checkArticleAPI,
  updateArticleAPI,
  publishArticleAPI,
} from "@/api/article";
export default {
  name: "ArticleTemplate",
  props: {
    mode: {
      type: String,
      validator: (v) => ["edit", "add"].includes(v),
      required: true,
    },
  },
  components: {
    UploadImg,
    Editor,
  },
  created() {
    this.getArticleCategoryLevel();
  },
  watch: {
    "$route.params": {
      handler(n, o) {
        if (this.mode === "edit") {
          this.getSingleArticle(n.id);
        }
      },
      immediate: true,
    },
  },
  data() {
    let validateHtmlContent = (r, v, c) => {
      const content = v.replace(/<[^>]*>/g, "").trim();
      let flag = content.length ? true : false;
      if (flag) {
        c();
      } else {
        c(new Error("文章内容不能为空"));
      }
    };
    return {
      categoryList: [],
      uploadimg: "",
      defaultCategoryId: "",
      articleForm: {
        createDate: "",
        title: "",
        htmlContent: "",
        description: "",
        thumb: "",
        categoryId: "",
        toc: [],
      },
      rules: {
        title: [
          { required: true, message: "文章标题为必填项", trigger: "blur" },
        ],
        htmlContent: [
          { required: true, message: "文章内容为必填项", trigger: "blur" },
          { validator: validateHtmlContent, trigger: "blur" },
        ],
        description: [
          { required: true, message: "文章描述为必填项", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "文章分类为必填项", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    getEditorHtml() {
      return this.$refs.editorRef.invoke("getHTML");
    },
    setEditorHtml(htmltext) {
      this.$refs.editorRef.invoke("setHTML", htmltext);
    },
    getMorkDown() {
      return this.$refs.editorRef.invoke("getMarkdoen");
    },
    async getArticleCategoryLevel() {
      const res = await getArticleCategoryAPI();
      if (typeof res !== "string") {
        this.categoryList = res.data;
        this.defaultCategoryId = res.data[0].id;
      } else {
        const { msg } = JSON.parse(res);
        this.$message.error(msg);
      }
    },

    handlerSubmitArticle() {
      this.articleForm.htmlContent = this.getEditorHtml();
      this.articleForm.createDate = Date.now();

      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.mode === "edit") {
            const res = await updateArticleAPI(
              this.articleForm.id,
              this.articleForm
            );
            if (typeof res !== "string") {
              this.$message.success("文章更新成功");
              this.$router.push({ path: "/article/articlelist" });
            } else {
              const { msg } = JSON.parse(res);
              this.$message.error(msg);
            }
          } else {
            const res = await publishArticleAPI(this.articleForm);
            if (typeof res !== "string") {
              this.$message.success("文章发布成功");
              this.$router.push({ path: "/article/articlelist" });
            } else {
              const { msg } = JSON.parse(res);
              this.$message.error(msg);
            }
          }
        } else {
          return false;
        }
      });
    },

    async getSingleArticle(id) {
      const res = await checkArticleAPI(id);
      if (typeof res !== "string") {
        this.articleForm = res.data;
        this.articleForm.categoryId = res.data.category
          ? res.data.category.id
          : this.defaultCategoryId;
        this.uploadimg = res.data.thumb ? setDevImg(res.data.thumb) : "";
        this.setEditorHtml(res.data.htmlContent);
      } else {
        const { msg } = JSON.parse(res);
        this.$message.error(msg);
      }
    },
    handlerArticleUpdate() {
      this.articleForm.htmlContent = this.getEditorHtml();
      this.articleForm.createDate = Date.now();
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await updateArticleAPI(
            this.articleForm.id,
            this.articleForm
          );
          if (typeof res !== "string") {
            this.$message.success("文章更新成功");
            this.$router.push({ path: "/article/articlelist" });
          } else {
            const { msg } = JSON.parse(res);
            this.$message.error(msg);
          }
        } else {
          return false;
        }
      });
    },
    handlerSelectChange() {
      this.$forceUpdate();
    },
  },
};
</script>

<style scoped lang="scss">
.addarticle-container {
  padding: 10px;
}
::v-deep .editor-container .el-form-item__content {
  line-height: unset !important;
}
::v-deep .textarea-input .el-textarea__inner {
  height: 200px;
  resize: none;
}
</style>
